const { exec, execSync } = require("child_process");
const { contextBridge } = require("electron");
const { getInstalledApps } = require("get-installed-apps");

// 内核版本信息
window.addEventListener("DOMContentLoaded", () => {
  ["chrome", "node", "electron"].forEach((item) => {
    console.log(`内核版本信息[${item}]: ${process.versions[item]}`);
  });
});

function fuzzyMatch(text, pattern) {
  const regex = new RegExp(pattern.split("").join(".*"), "i");
  return regex.test(text);
}

// 将electron的api绑定在window上从而提供给渲染器
contextBridge.exposeInMainWorld("electron", {
  // 搜索本地应用程序
  searchLocalApps: async (keyword) => {
    const apps = await getInstalledApps();
    const filterApps = apps.filter((item) => fuzzyMatch(item.appName, keyword) && item.appVersion);
    if (process.platform == "darwin") {
      return filterApps.map((item) => ({
        ...item,
        handleOpen: () => exec(`open ${filePath}`),
      }));
    } else {
      return filterApps.map((item) => ({
        ...item,
        handleOpen: () => {
          try {
            console.log(item.InstallLocation);
            execSync(`start ${item.InstallLocation}`);
            console.log("successfully!");
          } catch (error) {
            console.error(error.message);
          }
        },
      }));
    }
  },
});
